﻿using System;
using Const;
using UnityEngine;
using Random = UnityEngine.Random;

public class Cube : MonoBehaviour
{
    public GameObject down_head;
    public GameObject down_tail;
    public GameObject up;

    public int index;

    private Transform _transform;
    private Transform _upTransfrom;
    private Transform _downHeadTransform;
    private Transform _downTailTransfrom;

    private void Start()
    {
        _transform = transform;
        _upTransfrom = up.transform;
        _downHeadTransform = down_head.transform;
        _downTailTransfrom = down_tail.transform;

        Init();
        MyColor.SetMatrialColor(down_tail, "blue");
    }

    private void Update()
    {
        if (GameManager.ins.state == EState.ING)
        {
            if (GameManager.ins.isCross(_transform.position.x))
            {
                index += Param.cubeCount;
                Init();
            }
        }
    }

    public Vector3 LinkPos()
    {
        return new Vector3(_transform.position.x,
            _upTransfrom.position.y - 10f,
            _transform.position.z);
    }


    // ReSharper disable Unity.PerformanceAnalysis
    public void Init()
    {
        var offsetY = 1.3f;
        if (index < Param.cubeCount)
        {
            //前面15个让低一点
            offsetY = 1.4f;
        }

        var offsetUpY = Random.Range(0.1f, 0.3f) + 0.4f;
        var offsetDownY = offsetUpY - Random.Range(0.1f, 0.3f) - offsetY;

        _transform.position = new Vector3(index * Param.interval, 0, 0);

        _upTransfrom.localPosition = new Vector3(0, offsetUpY, 0);
        _downHeadTransform.localPosition = new Vector3(0, offsetDownY, 0);
        _downTailTransfrom.localPosition = new Vector3(0, offsetDownY, 50.5f);

        var color = index % 2 == 0 ? "blue_light" : "blue_dark";
        MyColor.SetMatrialColor(up, color);
        MyColor. SetMatrialColor(down_head,color);
    }
}